package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
        //前置过滤器
    }

    @Override
    public int filterOrder() {
        //该过滤器顺序要 > 5，才能得到 serviceid
        //zuul有5个默认的过滤器
        //在第五个过滤器中,向上下问对象添加了serviceID属性
        //后面的过滤器才能访问
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx=RequestContext.getCurrentContext();
        String serviceID = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(serviceID);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);

            String json = JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("NOT LOGIN! 未登录!")
                    .toString();
            ctx.addZuulRequestHeader(
                    "Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        //zuul当前版本中没有使用这个返回值,它不起人格作用
        return null;
    }
}
